package com.xuqm.sdhbwfu.app.ui

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.bigkoo.alertview.AlertView
import com.xuqm.base.adapter.CommonAdapter
import com.xuqm.base.adapter.ViewHolder
import com.xuqm.base.common.GsonImplHelp
import com.xuqm.base.common.ToolsHelper
import com.xuqm.base.dialog.loading.LoadingDialog
import com.xuqm.base.extensions.showMessage
import com.xuqm.base.ui.BaseActivity
import com.xuqm.sdhbwfu.app.R
import com.xuqm.sdhbwfu.app.databinding.ActivityProcessingBinding
import com.xuqm.sdhbwfu.app.model.JobListModel
import com.xuqm.sdhbwfu.app.viewmodel.JobProcessingViewModel
import com.xuqm.sdhbwfu.core.extensions.addItemDecorationForVertical

class ProcessingActivity : BaseActivity<ActivityProcessingBinding>() {
    override fun getLayoutId(): Int = R.layout.activity_processing
    override fun fullscreen(): Boolean = true

    private var mId: Int = -1
    private val vm: JobProcessingViewModel by viewModels()

    private val mData = mutableListOf<JobListModel>()
    private var modelp = -1

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        binding.jobListRv.layoutManager = LinearLayoutManager(mContext)
        binding.jobListRv.addItemDecorationForVertical(10)
        binding.jobListRv.adapter = adapter
    }

    override fun lateInitView() {
        super.lateInitView()
        binding.inspectionBackLyt.setOnClickListener { finish() }
        binding.processingBtn.setOnClickListener {
            if (-1 != modelp) {
                startActivityForResult(
                    Intent(
                        mContext,
                        ProcessingDetailActivity::class.java
                    ).apply {
                        putExtra("mId", mId)
                        putExtra("item", GsonImplHelp.get().toJson(mData[modelp]))
                    }, 10086
                )
            } else {
                "当前任务已全部完成".showMessage()
            }
        }
        binding.processingConfirm.setOnClickListener {
            if (-1 == modelp) {
                LoadingDialog.showDialog("")
                vm.inspectionConfirm(mId)
            } else {
                "当前还有未完成的任务".showMessage()
            }
        }
    }

    override fun initData() {
        super.initData()
        mId = intent.getIntExtra("id", -1)
        if (-1 == mId) {
            AlertView(
                "", "获取任务信息失败",
                null, arrayOf("确定"), null, mContext,
                AlertView.Style.Alert
            ) { _, _ ->
                finish()
            }.show()
        }
        vm.list.observe(this) {
            mData.addAll(it)
            mData.sortedBy { item -> item.sort }
            adapter.notifyDataSetChanged()
            updateHint()
        }
        vm.status.observe(this) {
            if (null != it) {
                "提交完成".showMessage()
                finish()
            }
        }

        vm.inspectionList(mId)
    }

    private fun updateHint() {

        val undo = mData.filter { its -> its.status.isNullOrEmpty() }.size
        binding.jobUndoTv.text = "$undo"
        binding.jobDoneTv.text = "${mData.size - undo}"
        binding.jobAllTv.text = "${mData.size}"
    }

    private val adapter =
        object : CommonAdapter<JobListModel>(R.layout.item_job_list, mData) {
            override fun convert(holder: ViewHolder, item: JobListModel, position: Int) {
                holder.setBackgroundColor(R.id.item_app, Color.parseColor("#DBE3E6"))
                holder.setText(R.id.item_job_no, "${position + 1}")
                holder.setText(R.id.item_job_num, "${item.itemValue.size}")
                holder.setText(R.id.item_job_name, item.name)
                holder.setText(
                    R.id.item_job_status, when (ToolsHelper.toString(item.status)) {
                        "skip" -> "跳过"
                        "finished" -> "完成"
                        else -> {
                            if (-1 == modelp) {
                                modelp = position
                            }
                            "未完成"
                        }
                    }
                )
                holder.setText(R.id.item_job_obj, item.concreteName)
                holder.setText(
                    R.id.item_job_type, when (item.projectType) {
                        "location" -> "位置"
                        "asset" -> "资产"
                        else -> ""
                    }
                )
            }

        }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 10086) {
            if (resultCode == RESULT_OK) {
                val model = GsonImplHelp.get()
                    .toObject(data?.getStringExtra("item"), JobListModel::class.java)
                if (null != model)
                    mData[modelp] = model
                modelp = -1
                adapter.notifyDataSetChanged()
                updateHint()
            }
        }
    }
}